package models

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"strings"
)

// 定义 API 请求的结构体
type DeepSeekRequest struct {
	Model            string           `json:"model"`
	Messages         []MessageRequest `json:"messages"`
	FrequencyPenalty float64          `json:"frequency_penalty"`
	MaxTokens        int              `json:"max_tokens"`
	PresencePenalty  float64          `json:"presence_penalty"`
	ResponseFormat   ResponseFormat   `json:"response_format"`
	Stop             interface{}      `json:"stop"`
	Stream           bool             `json:"stream"`
	StreamOptions    interface{}      `json:"stream_options"`
	Temperature      float64          `json:"temperature"`
	TopP             float64          `json:"top_p"`
	Tools            []interface{}    `json:"tools"`
	ToolChoice       string           `json:"tool_choice"`
	Logprobs         bool             `json:"logprobs"`
	TopLogprobs      interface{}      `json:"top_logprobs"`
}

type MessageRequest struct {
	Content string `json:"content"`
	Role    string `json:"role"`
}

type ResponseFormat struct {
	Type string `json:"type"`
}

type ScoreItem struct {
	Title string `json:"title"`
	Score string `json:"score"`
}

type Data struct {
	LMG      ScoreItem `json:"LMG"`
	LAC      ScoreItem `json:"LAC"`
	LMS      ScoreItem `json:"LMS"`
	LES      ScoreItem `json:"LES"`
	LAE      ScoreItem `json:"LAE"`
	LSA      ScoreItem `json:"LSA"`
	LHSM     ScoreItem `json:"LHSM"`
	LSC      ScoreItem `json:"LSC"`
	SVE      ScoreItem `json:"SVE"`
	SBS      ScoreItem `json:"SBS"`
	SRE      ScoreItem `json:"SRE"`
	Analysis ScoreItem `json:"Analysis"`
}

type Choices struct {
	Index        int         `json:"index"`
	Message      Message     `json:"message"`
	Logprobs     interface{} `json:"logprobs"`
	FinishReason string      `json:"finish_reason"`
}

type Message struct {
	Role    string `json:"role"`
	Content string `json:"content"`
}

type Usage struct {
	PromptTokens        int `json:"prompt_tokens"`
	CompletionTokens    int `json:"completion_tokens"`
	TotalTokens         int `json:"total_tokens"`
	PromptTokensDetails struct {
		CachedTokens int `json:"cached_tokens"`
	} `json:"prompt_tokens_details"`
	PromptCacheHitTokens  int `json:"prompt_cache_hit_tokens"`
	PromptCacheMissTokens int `json:"prompt_cache_miss_tokens"`
}

type Response struct {
	ID                string    `json:"id"`
	Object            string    `json:"object"`
	Created           int       `json:"created"`
	Model             string    `json:"model"`
	Choices           []Choices `json:"choices"`
	Usage             Usage     `json:"usage"`
	SystemFingerprint string    `json:"system_fingerprint"`
}

// StudentAnswer 学生答案结构
type StudentAnswer struct {
	Question string `json:"question"`
	Answer   string `json:"answer"`
	Index    int    `json:"index"`
}

func CallDeepSeek(userPrompt, analysis_prompt string, kind int8) (analysis string, err error) {
	// 你的 API 密钥
	apiKey := "sk-a11678f4335e4097bbeb7fb79431afb1"
	if analysis_prompt == "" {
		analysis_prompt = "本次访谈的综合评估分析"
	}

	url := "https://api.deepseek.com/chat/completions"
	method := "POST"
	// 定义 system_prompt 和 user_prompt
	systemPrompt := ``
	switch kind {
	case 0:
		systemPrompt = `
		以下是对学生的访谈对话,请对访谈内容进行分析,并对此学生按以下json格式中的维度进行评估得分(100分制)和总结:
		{
			"LMG": {
			  "title": "学习动力与目标",
			  "score": "得分"
			},
			"LAC": {
			  "title": "学习态度与认知",
			  "score": "得分"
			},
			"LMS": {
			  "title": "学习方法与策略",
			  "score": "得分"
			},
			"LES": {
			  "title": "学习情绪与压力",
			  "score": "得分"
			},
			"LAE": {
			  "title": "学习成果与期望",
			  "score": "得分"
			},
			"LSA": {
			  "title": "生活满意度与态度",
			  "score": "得分"
			},
			"LHSM": {
			  "title": "生活习惯与自我管理",
			  "score": "得分"
			},
			"LSC": {
			  "title": "生活压力与应对",
			  "score": "得分"
			},
			"SVE": {
			  "title": "社交价值观与期望",
			  "score": "得分"
			},
			"SBS": {
			  "title": "社交行为与技巧",
			  "score": "得分"
			},
			"SRE": {
			  "title": "社交关系与情绪",
			  "score": "得分"
			},
			"Analysis": {
				"title": ` + analysis_prompt + `,  
				"score": "大约300字的综合评估分析"
			}
		}
		`
	case 1:
		systemPrompt = `以下是对学生出国留学意愿的访谈对话,请对访谈内容进行分析该学生有无潜在出国意愿，不愿留学的原因是什么，需要辅导老师做哪些工作提供支持:`
	}

	// 使用结构体定义 requestBody
	requestBody := DeepSeekRequest{
		Model: "deepseek-chat",
		Messages: []MessageRequest{
			{
				Content: systemPrompt,
				Role:    "system",
			},
			{
				Content: userPrompt,
				Role:    "user",
			},
		},
		FrequencyPenalty: 0,
		MaxTokens:        2048,
		PresencePenalty:  0,
		ResponseFormat: ResponseFormat{
			Type: "json_object",
		},
		Stop:          nil,
		Stream:        false,
		StreamOptions: nil,
		Temperature:   1,
		TopP:          1,
		Tools:         nil,
		ToolChoice:    "none",
		Logprobs:      false,
		TopLogprobs:   nil,
	}
	var requestBodyBytes []byte
	// 将请求体转换为 JSON
	requestBodyBytes, err = json.Marshal(requestBody)
	if err != nil {
		err = fmt.Errorf("error marshaling request body:%v", err)
		return
	}
	// 创建 HTTP 请求
	client := &http.Client{}
	var req *http.Request
	req, err = http.NewRequest(method, url, bytes.NewBuffer(requestBodyBytes))
	if err != nil {
		err = fmt.Errorf("error creating request:%s", err.Error())
		return
	}
	// 设置请求头
	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("Accept", "application/json")
	req.Header.Add("Authorization", "Bearer "+apiKey) // 替换为你的 API 密钥

	// 发送请求
	var res *http.Response
	res, err = client.Do(req)
	if err != nil {
		err = fmt.Errorf("error sending request:%s", err.Error())
		return
	}
	defer res.Body.Close()

	// 读取响应
	var body []byte
	body, err = io.ReadAll(res.Body)
	if err != nil {
		err = fmt.Errorf("error reading response body:%v", err)
		return
	}
	// {"error":{"message":"Insufficient Balance","type":"unknown_error","param":null,"code":"invalid_request_error"}}

	fmt.Println("===:", string(body))
	if strings.Contains(string(body), `{"error"`) {
		err = fmt.Errorf("AI Error: %v", string(body))
		return
	}
	var response Response
	err = json.Unmarshal(body, &response)
	if err != nil {
		err = fmt.Errorf("error unmarshalling JSON: %v", err)
		return
	}
	if len(response.Choices) == 0 {
		err = fmt.Errorf("response.Choices 长度为%d", 0)
		return
	}
	analysis = response.Choices[0].Message.Content
	return
}

// ExamDeepSeek 调用deepseek的接口判定学生的问答是否正确，并给出总分100分的评分
func ExamDeepSeek(userAnswers []StudentAnswer) (score float64, analysis string, err error) {
	// 构建用户提问内容
	var userPrompt strings.Builder
	userPrompt.WriteString("请根据以下问题和学生答案进行评估，并给出总分100分的评分：\n")
	
	for _, answer := range userAnswers {
		userPrompt.WriteString(fmt.Sprintf("问题%d: %s\n", answer.Index, answer.Question))
		userPrompt.WriteString(fmt.Sprintf("学生答案: %s\n\n", answer.Answer))
	}

	// 你的 API 密钥
	apiKey := "sk-a11678f4335e4097bbeb7fb79431afb1"

	url := "https://api.deepseek.com/chat/completions"
	method := "POST"
	
	// 定义 system_prompt
	systemPrompt := `你是一位专业的考试评分师，请根据问题和参考答案来评估学生的回答。
请按照以下要求进行评分：
1. 内容准确性（40分）：答案是否准确回答了问题要点
2. 内容完整性（30分）：答案是否涵盖了问题的所有重要方面
3. 逻辑清晰度（20分）：答案组织是否条理清晰、逻辑连贯
4. 表达质量（10分）：语言表达是否准确流畅

最终给出一个总分（满分100分）和简要评语。

请以严格的JSON格式返回结果，格式如下：
{
  "score": 85,
  "comment": "评语内容"
}`

	// 使用结构体定义 requestBody
	requestBody := DeepSeekRequest{
		Model: "deepseek-chat",
		Messages: []MessageRequest{
			{
				Content: systemPrompt,
				Role:    "system",
			},
			{
				Content: userPrompt.String(),
				Role:    "user",
			},
		},
		FrequencyPenalty: 0,
		MaxTokens:        2048,
		PresencePenalty:  0,
		ResponseFormat: ResponseFormat{
			Type: "json_object",
		},
		Stop:          nil,
		Stream:        false,
		StreamOptions: nil,
		Temperature:   0.7, // 降低温度使输出更稳定
		TopP:          1,
		Tools:         nil,
		ToolChoice:    "none",
		Logprobs:      false,
		TopLogprobs:   nil,
	}
	
	var requestBodyBytes []byte
	// 将请求体转换为 JSON
	requestBodyBytes, err = json.Marshal(requestBody)
	if err != nil {
		err = fmt.Errorf("error marshaling request body:%v", err)
		return
	}
	
	// 创建 HTTP 请求
	client := &http.Client{}
	var req *http.Request
	req, err = http.NewRequest(method, url, bytes.NewBuffer(requestBodyBytes))
	if err != nil {
		err = fmt.Errorf("error creating request:%s", err.Error())
		return
	}
	
	// 设置请求头
	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("Accept", "application/json")
	req.Header.Add("Authorization", "Bearer "+apiKey) // 替换为你的 API 密钥

	// 发送请求
	var res *http.Response
	res, err = client.Do(req)
	if err != nil {
		err = fmt.Errorf("error sending request:%s", err.Error())
		return
	}
	defer res.Body.Close()

	// 读取响应
	var body []byte
	body, err = io.ReadAll(res.Body)
	if err != nil {
		err = fmt.Errorf("error reading response body:%v", err)
		return
	}
	
	// 检查错误响应
	if strings.Contains(string(body), `{"error"`) {
		err = fmt.Errorf("AI Error: %v", string(body))
		return
	}
	
	var response Response
	err = json.Unmarshal(body, &response)
	if err != nil {
		err = fmt.Errorf("error unmarshalling JSON: %v", err)
		return
	}
	
	if len(response.Choices) == 0 {
		err = fmt.Errorf("response.Choices 长度为%d", 0)
		return
	}
	
	analysis = response.Choices[0].Message.Content
	
	// 解析返回的分数
	var result map[string]interface{}
	err = json.Unmarshal([]byte(analysis), &result)
	if err != nil {
		err = fmt.Errorf("无法解析AI返回的结果: %v", err)
		return
	}
	
	scoreValue, ok := result["score"].(float64)
	if !ok {
		err = fmt.Errorf("无法从AI返回中提取分数")
		return
	}
	
	score = scoreValue
	return
}